package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Exam;
import com.eduadmin.service.IExamService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExamDataUploadListener extends AnalysisEventListener<Exam> {
    private  int count=1;
    //依赖注入
    private final IExamService examService;
    public ExamDataUploadListener(IExamService examService) {
        this.examService = examService;
    }

    private static final int BATCH_COUNT = 600;
    List<Exam> list = new ArrayList<>();

    @Override
    public void invoke(Exam data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        count++;
        Map<String,Object> paraMap=new HashMap<>();
        paraMap.put("gradeName",data.getGradeName());
        paraMap.put("semesterName",data.getSemesterName());
        paraMap.put("examName",data.getExamName());
        Exam exam= examService.getExamByParams(paraMap);// zlc 更改2021-12-17
        if(exam==null){
        list.add(data);
        }else {
            log.info("Excel 数据表中第 "+count + " 行 的考试名称已在数据库中，不能再导入！");
        }

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            examService.addExams(list);
        }
        log.info("存储数据库成功！");
    }


}
